package com.topsec.manager.util;

import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by huangyongqiang
 * Created with JDK：1.7.0_71
 * Created with IntelliJ IDEA
 * Date: 2018-01-26 11:13
 *
 * @类说明：截取url的工具类
 */
public class SplitUrl {

    /**
     * @param args
     * @author wiksys
     */
    public static void main(String[] args) {

        //splitUrls("http://www.baidu.com:8080/index.jsp");
        //splitUrls("ftp://baidu.com/pub/index.jsp");
        //splitUrls("baidu.com/pub/index.jsp");
        //splitUrls("http://baidu.com:8080");
        //splitUrls("http://baidu.com");
        //splitUrls("baidu");

        String[] baidus = splitUrls("baidu");
        System.out.println(baidus[0]);
        System.out.println(baidus[1]);
        System.out.println(baidus[2]);
        System.out.println(baidus[3]);


        //String url = "http://sports.sina.com.cn/";
        //String[] sub_url_array = url.split("[/ : . - _ # %]");
        //int sid;
        //for (sid = 0; sid < sub_url_array.length; sid++) {
        //    if (sub_url_array[sid].equals("")) continue;
        //    System.out.println(sub_url_array[sid]);
        //}
        //
        //
        //// 请求url
        ////String str = "index.jsp?Action=del&id=123&sort=";
        //String str = "http://www.baidu.com/index.jsp";
        //
        ////url页面路径
        //System.out.println(UrlPage(str));
        //
        ////url参数键值对
        //String strRequestKeyAndValues = "";
        //Map<String, String> mapRequest = URLRequest(str);
        //
        //for (String strRequestKey : mapRequest.keySet()) {
        //    String strRequestValue = mapRequest.get(strRequestKey);
        //    strRequestKeyAndValues += "key:" + strRequestKey + ",Value:" + strRequestValue + ";";
        //
        //}
        //System.out.println(strRequestKeyAndValues);
        //
        ////获取无效键时，输出null
        //System.out.println(mapRequest.get("page"));
    }


    /**
     * 分割url
     * <p>
     * 例:http://www.baidu.com:8080/index.jsp
     * 端口: 8080
     * 协议: http://
     * 网址：www.baidu.com
     * 内容：/index.jsp
     *
     * @param url
     */
    public static String[] splitUrls(String url) {

        String[] rere = new String[4];

        // 端口
        String port = "";
        // 协议
        String proto = "";
        // 网址
        String webUrl = "";
        // 内容
        String context = "";

        // 判断 (得到第一次遇到的 // 的值之前的字符串的长度)
        int firSplit = url.indexOf("//");

        // 判断url是否内容 (从第 x 位开始遇到 / 的值之前的字符串的长度)
        int webSplit = url.indexOf("/", firSplit + 2);

        // 判断端口是否存在 (从第 x 位开始遇到 ： 的值之前的字符串的长度)
        int portIndex = url.indexOf(":", firSplit);


        // 判断协议是否存在
        if (-1 != firSplit) {
            proto = url.substring(0, firSplit + 2);                         // 截取协议(http:// 或 https://)

            // 网址中含有其他路径
            if (-1 != webSplit) {
                webUrl = url.substring(firSplit + 2, webSplit);             // 截取 / 前的url(包含端口)

                // 判断端口是否存在
                if (portIndex >= 0) {
                    webUrl = webUrl.substring(0, webUrl.indexOf(":"));      // 截取url(减去：后面的数据)
                    port = url.substring(portIndex + 1, webSplit);          // 截取 端口
                }
                context = url.substring(webSplit, url.length());
            } else {
                webUrl = url.substring(firSplit + 2);                       // 截取 url(包含端口)
                // 判断端口是否存在
                if (portIndex >= 0) {
                    webUrl = webUrl.substring(0, webUrl.indexOf(":"));      // 截取url(减去：后面的数据)
                    port = url.substring(portIndex + 1, url.length());      // 截取 端口
                }
            }

        } else {

            if (-1 != webSplit) {
                webUrl = url.substring(firSplit + 1, webSplit);

                if (portIndex >= 0) {
                    webUrl = webUrl.substring(0, webUrl.indexOf(":"));
                    port = url.substring(portIndex + 1, webSplit);
                }
                context = url.substring(webSplit);

            } else {
                // 只有内容
                webUrl = url.substring(firSplit + 1, webSplit + 1);

                if (portIndex >= 0) {
                    webUrl = webUrl.substring(0, webUrl.indexOf(":"));
                    port = url.substring(portIndex + 1, webSplit);
                }
                context = url.substring(webSplit + 1);
            }
        }

        rere[0] = port;
        rere[1] = proto;
        rere[2] = webUrl;
        rere[3] = context;

        return rere;
    }

    /**
     * 分割email
     *
     * @param email
     * @return
     */
    public List<String> regexEmail(String email) {

        List<String> groups = new ArrayList<String>();

        Pattern pattern = Pattern.compile("^(.*)( (-|(\\w)|(\\.))+@[a-zA-Z0-9_-]+(\\.[a-zA-Z0-9_-]+)+)(.*)$");
        Matcher matcher = pattern.matcher(email);

        if (matcher.find()) {
            int start = matcher.start(2);
            int end = matcher.end(2);

            groups.add(email.substring(0, start));
            groups.add(email.substring(start, end));
            groups.add(email.substring(end, email.length()));
        }

        return groups;
    }

    /**
     * 分割email
     *
     * @param url
     * @return
     */
   /* public static List<String> regexURL(String url) {

        List<String> groups = new ArrayList<String>();

        Pattern pattern = Pattern.compile("^(https?|ftp|file)://[-A-Za-z0-9+&@#/%?=~_|!:,.;]+[-A-Za-z0-9+&@#/%=~_|]$");
        Matcher matcher = pattern.matcher(url);

        if (matcher.find()) {
            System.out.println(matcher.group(1));
            System.out.println(matcher.group(2));
            System.out.println(matcher.group(3));
        }

        return groups;
    }*/

    /**
     * 解析出url请求的路径，包括页面
     *
     * @param strURL url地址
     * @return url路径
     */
    public static String UrlPage(String strURL) {
        String strPage = null;
        String[] arrSplit = null;

        strURL = strURL.trim().toLowerCase();

        arrSplit = strURL.split("[?]");
        if (strURL.length() > 0) {
            if (arrSplit.length > 1) {
                if (arrSplit[0] != null) {
                    strPage = arrSplit[0];
                }
            }
        }

        return strPage;
    }

    /**
     * 去掉url中的路径，留下请求参数部分
     *
     * @param strURL url地址
     * @return url请求参数部分
     */
    private static String TruncateUrlPage(String strURL) {
        String strAllParam = null;
        String[] arrSplit = null;

        strURL = strURL.trim().toLowerCase();

        arrSplit = strURL.split("[?]");
        if (strURL.length() > 1) {
            if (arrSplit.length > 1) {
                if (arrSplit[1] != null) {
                    strAllParam = arrSplit[1];
                }
            }
        }

        return strAllParam;
    }

    /**
     * 解析出url参数中的键值对
     * 如 "index.jsp?Action=del&id=123"，解析出Action:del,id:123存入map中
     *
     * @param URL url地址
     * @return url请求参数部分
     */
    public static Map<String, String> URLRequest(String URL) {
        Map<String, String> mapRequest = new HashMap<String, String>();

        String[] arrSplit;

        String strUrlParam = TruncateUrlPage(URL);
        if (strUrlParam == null) {
            return mapRequest;
        }
        //每个键值为一组 www.2cto.com
        arrSplit = strUrlParam.split("[&]");
        for (String strSplit : arrSplit) {
            String[] arrSplitEqual = null;
            arrSplitEqual = strSplit.split("[=]");

            //解析出键值
            if (arrSplitEqual.length > 1) {
                //正确解析
                mapRequest.put(arrSplitEqual[0], arrSplitEqual[1]);

            } else {
                if (arrSplitEqual[0] != "") {
                    //只有参数没有值，不加入
                    mapRequest.put(arrSplitEqual[0], "");
                }
            }
        }
        return mapRequest;
    }


}